<template>
  <div>
    <el-row>
      <el-col :span="24" class="flex justify-end">
        <el-radio-group v-model="type" @change="getData">
          <el-radio-button label="本日" value="本日" />
          <el-radio-button label="本周" value="本周" />
          <el-radio-button label="本月" value="本月" />
        </el-radio-group>
      </el-col>
      <template v-for="(item, index) in cards" :key="item.title">
        <el-col :span="24">
          <div class="head">
            <div class="title">{{ item.title }}</div>
            <div class="action">
              <el-dropdown trigger="click" :teleported="false" :hide-on-click="false">
                <el-icon><MoreFilled /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleHide(item, index)">隐藏</el-dropdown-item>
                    <el-dropdown-item>
                      <el-dropdown>
                        添加区块
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item
                              @click="handleAdd(i, index)"
                              v-for="i in hiddenList"
                              :key="i.title"
                              >{{ i.title }}</el-dropdown-item
                            >
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <component :is="item.component" :data="item.data" />
        </el-col>
      </template>
    </el-row>
    <div class="mt-20px w-100%">
      <DisplayChart
        ref="reportChartRef"
        :start-time="queryParams.startTime"
        :end-time="queryParams.endTime"
      />
    </div>
  </div>
</template>
<script setup>
// import DisplayChart from '@/views/report/display/homeIndex.vue'
import DisplayChart from '@/views/report/display/index2.vue'
import { MoreFilled } from '@element-plus/icons-vue'
import WorkBench from './components/WorkBench.vue'
import Notice from './components/Notice.vue'
import DatabaseAsset from './components/DatabaseAsset.vue'
import FileAsset from './components/FileAsset.vue'
import DataProduct from './components/DataProduct.vue'
import AttributionSystem from './components/AttributionSystem.vue'
import Dept from './components/Dept.vue'
import {
  getClassificationStatistics,
  getDeptStatistics,
  getLevelStatistics,
  getStandardStatistics,
  getSystemStatistics,
  getTaskStatistics
} from '@/api/home/index'
import { getNoticePage } from '@/api/system/notice/index'
import { getTime } from './getTime'
import dayjs from 'dayjs'
import { useCache } from '@/hooks/web/useCache'
import { defaultSetting } from './setting'
import { useAppStore } from '@/store/modules/app'

const reportChartRef = ref()
const handleHide = (item, index) => {
  homeSetting.value.forEach((i) => {
    if (i.title === item.title) {
      i.hidden = true
    }
  })
  cards.value.splice(index, 1)
}
const handleAdd = (item, index) => {
  const obj = titleMap.get(item.title)
  cards.value.splice(index + 1, 0, {
    title: item.title,
    component: obj.component,
    data: obj.data
  })
}
const type = ref('本日')
const databaseAsset = reactive({
  level: [],
  sort: []
})
const fileAsset = reactive({
  level: [],
  sort: []
})
const productData = ref([])
const systemData = reactive({
  tableData: [],
  daTotal: 0,
  fileTotal: 0
})
const deptData = reactive({
  tableData: [],
  daTotal: 0,
  fileTotal: 0
})

const noticeData = ref([])
const taskData = ref({})

const appStore = useAppStore()
const homeSetting = computed({
  get() {
    return appStore.getHomeSetting || defaultSetting
  },
  set(val) {
    appStore.setHomeSetting(val)
  }
})

// 标题对应组件和数据
const titleMap = new Map([
  ['工作台', { data: taskData, component: WorkBench }],
  ['消息提醒', { data: noticeData, component: Notice }]
  // ['数据库资产分类分级', { data: databaseAsset, component: DatabaseAsset }],
  // ['文件资产分类分级', { data: fileAsset, component: FileAsset }],
  // ['数据保护标准', { data: productData, component: DataProduct }],
  // ['归属系统分析', { data: systemData, component: AttributionSystem }],
  // ['归属机构', { data: deptData, component: Dept }]
])

const hiddenList = computed(() => {
  const arr = []
  homeSetting.value.forEach((item) => {
    if (item.hidden) {
      arr.push(item)
    }
  })
  return arr
})

const cards = ref([])
watch(
  () => cards.value.length,
  () => {
    cards.value.forEach((c, index) => {
      for (let i of homeSetting.value) {
        if (i.title === c.title) {
          i.sort = index
          i.hidden = false
          return
        }
      }
    })
    homeSetting.value = homeSetting.value
  }
)
// 初始化数据
const initHomeSetting = () => {
  cards.value = homeSetting.value
    .filter((item) => !item.hidden)
    .sort((a, b) => a.sort - b.sort)
    .map((item) => {
      const obj = titleMap.get(item.title) || {}
      return {
        title: item.title,
        component: obj.component,
        data: obj.data
      }
    })
}
initHomeSetting()

const queryParams = ref({
  startTime: '',
  endTime: ''
})

const getClassification = async () => {
  const res = await getClassificationStatistics(queryParams.value)
  const databaseSort = []
  const fileSort = []
  res.forEach((item) => {
    databaseSort.push({
      name: item.name,
      value: item.dbCount
    })
    fileSort.push({
      name: item.name,
      value: item.fileCount
    })
  })
  databaseAsset.sort = databaseSort
  fileAsset.sort = fileSort
}
const getDept = async () => {
  const res = await getDeptStatistics(queryParams.value)
  let fileTotal = 0
  let dbTotal = 0
  res.forEach((item) => {
    fileTotal += item.fileCount
    dbTotal += item.dbCount
  })
  deptData.tableData = recombinationData(res)
  deptData.fileTotal = fileTotal
  deptData.dbTotal = dbTotal
}
const getLevel = async () => {
  const res = await getLevelStatistics(queryParams.value)
  const databaseLevel = []
  const fileLevel = []
  res.forEach((item) => {
    databaseLevel.push({
      name: item.name,
      value: item.dbCount
    })
    fileLevel.push({
      name: item.name,
      value: item.fileCount
    })
  })
  databaseAsset.level = databaseLevel
  fileAsset.level = fileLevel
}
const getStandard = async () => {
  const res = await getStandardStatistics(queryParams.value)
  productData.value = res
}
const getSystem = async () => {
  const res = await getSystemStatistics(queryParams.value)
  let fileTotal = 0
  let dbTotal = 0
  res.forEach((item) => {
    fileTotal += item.fileCount
    dbTotal += item.dbCount
  })
  systemData.tableData = recombinationData(res)
  systemData.fileTotal = fileTotal
  systemData.dbTotal = dbTotal
}

// 重组数据
const recombinationData = (data) => {
  for (let i of data) {
    for (let j of data) {
      if (j.parentId == i.id) {
        if (i.children) {
          i.children.push(j)
        } else {
          i.children = [j]
        }
      }
    }
  }
  const result = data.filter((item) => item.parentId == 0)
  console.log('result', result)
  return result
}

const getNotice = async () => {
  const { data } = await getNoticePage({ ...queryParams.value, status: 0 })
  noticeData.value = data
}
const getTask = async () => {
  const res = await getTaskStatistics(queryParams.value)
  taskData.value = res
}
const getAll = () => {
  getClassification()
  getDept()
  getLevel()
  getStandard()
  getSystem()
  getNotice()
  getTask()
}

onActivated(() => {
  getData()
})

const getData = () => {
  let res = []
  switch (type.value) {
    case '本日':
      res = getTime().getToday()
      break
    case '本周':
      res = getTime().getWeek()
      break
    default:
      res = getTime().getMonth()
      break
  }
  queryParams.value.startTime = dayjs(res[0]).format('YYYY-MM-DD HH:mm:ss')
  queryParams.value.endTime = dayjs(res[1]).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
  getAll()
}
getData()
</script>
<style lang="scss" scoped>
.head {
  display: flex;
  justify-content: space-between;
  margin: 12px 0;
  .title {
    border-left: 6px solid #409eff;
    padding-left: 12px;
    font-weight: bold;
  }
  .action {
    cursor: pointer;
  }
}
</style>
